
import Vue from 'vue'
import Vuex from 'vuex'
import config from '@/common/config.js'
import storage, { storageData } from '@/utils/storage.js'
import getters from './getters'
import user from './modules/user'
Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    user
  },
	state: {
		// 如果上面从本地获取的vita对象下有对应的属性，就赋值给state中对应的变量
		// 加上vuex_前缀，是防止变量名冲突
		vuex_mode: storageData.vuex_mode ? storageData.vuex_mode : '',
		vuex_token: storageData.vuex_token ? storageData.vuex_token : '',
		vuex_user: storageData.vuex_user ? storageData.vuex_user : { userName: '' },
		vuex_users: storageData.vuex_users ? storageData.vuex_users : '',
		vuex_remember: storageData.vuex_remember ? storageData.vuex_remember : '',
		vuex_locale: storageData.vuex_locale ? storageData.vuex_locale : '',
		vuex_isAgent: storageData.vuex_isAgent ? storageData.vuex_isAgent : '',
		// 如果vuex_version无需保存到本地永久存储，无需vita.vuex_version方式
		vuex_config: { ...config, ...storageData.vuex_config },
		// 自定义tabbar数据
		// vuex_tabbar: [{
		// 		iconPath: "/static/uview/example/component.png",
		// 		selectedIconPath: "/static/uview/example/component_select.png",
		// 		text: '组件',
		// 		pagePath: '/pages/example/components'
		// 	},
		// 	{
		// 		iconPath: "/static/uview/example/js.png",
		// 		selectedIconPath: "/static/uview/example/js_select.png",
		// 		text: '工具',
		// 		midButton: true,
		// 		pagePath: '/pages/example/js'
		// 	},
		// 	{
		// 		iconPath: "/static/uview/example/template.png",
		// 		selectedIconPath: "/static/uview/example/template_select.png",
		// 		text: '模板',
		// 		pagePath: '/pages/example/template'
		// 	}
		// ]
	},
	mutations: {
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.')
			let saveKey = ''
			let len = nameArr.length
			if (len >= 2) {
				let obj = state[nameArr[0]]
				for(let i = 1; i < len - 1; i ++) {
					obj = obj[nameArr[i]]
				}
				obj[nameArr[len - 1]] = payload.value
				saveKey = nameArr[0]
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value
				saveKey = payload.name
			}
			// 保存变量到本地，见顶部函数定义
			storage.set(saveKey, state[saveKey])
		}
	},
	getters
})

export default store
